<!--
 * @Author: your name
 * @Date: 2021-04-04 23:28:33
 * @LastEditTime: 2021-04-06 20:15:11
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \JavaScript\04 - 深浅克隆.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>深浅克隆</title>
</head>
<body>
  <script>
    let obj1 = {
      a: 0,
      b: '1',
      c: [3, 4, 5],
      d: {
        val: 10
      },
      e: /^\d/,
      f: new Date()
    }
    let obj2 = {}
    // 1.浅克隆
    // obj2 = { ...obj1 }
    // 2.深克隆
    // obj2 = JSON.parse(JSON.stringify(obj1)) // 缺点是正则表达式变成了空对象，日期格式变了

    // 3.自己写一个深克隆
    function deepClone(obj) {
      // 过滤特殊情况
      if (obj === null) return null
      if (typeof obj === 'object') return obj
      if (obj instanceof RegExp) return new RegExp(obj) // 保持原来的累次那个
      if (obj instanceof Date) return new Date(obj)
      // 不直接创建空对象的目的：克隆的结果和之前的保持相同的所属类
      let newObj = new obj.constructor
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = deepClone(obj[key]) // 递归
        }
      }
      return newObj
    }
    obj2 = deepClone(obj1)
    console.log(obj1, obj2);
  </script>
</body>
</html>